import os
import shutil
from pathlib import Path

# ============================
# 配置区
# ============================
# 需要处理的文件夹列表（支持多个）
input_folders = [
    r"E:\nginx\fileload\PaddleX_OCR\4\imgs",
    r"E:\nginx\fileload\PaddleX_OCR\6\imgs",
    r"E:\nginx\fileload\PaddleX_OCR\5\imgs",
    r"E:\nginx\fileload\PaddleX_OCR\7\imgs",
    # r"E:\nginx\fileload\PaddleX_OCR\005\imgs",
    # r"E:\nginx\fileload\PaddleX_OCR\006\imgs",
    # r"E:\nginx\fileload\PaddleX_OCR\007\imgs"
]

# 输出文件夹路径
output_dir = r"E:\output_image"

# 是否递归搜索子文件夹
recursive = False  # True 表示会扫描子文件夹

# 是否移动文件（False 表示复制）
move_files = False

# ============================
# 程序逻辑
# ============================
supported_ext = (".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp", ".gif")

os.makedirs(output_dir, exist_ok=True)
counter = 1

def iter_images(folder_path, recursive=False):
    """生成器：返回文件夹下所有图片路径"""
    p = Path(folder_path)
    if recursive:
        return (fp for fp in p.rglob("*") if fp.suffix.lower() in supported_ext)
    else:
        return (fp for fp in p.iterdir() if fp.is_file() and fp.suffix.lower() in supported_ext)

for folder in input_folders:
    if not os.path.exists(folder):
        print(f"⚠️ 跳过，不存在: {folder}")
        continue

    print(f"📂 正在处理文件夹: {folder}")
    for img_path in iter_images(folder, recursive=recursive):
        try:
            ext = img_path.suffix.lower()
            new_name = f"img_{counter:06d}{ext}"
            dest_path = os.path.join(output_dir, new_name)

            if move_files:
                shutil.move(img_path, dest_path)
                action = "移动"
            else:
                shutil.copy2(img_path, dest_path)
                action = "复制"

            print(f"{action}: {img_path} → {dest_path}")
            counter += 1
        except Exception as e:
            print(f"❌ 处理失败: {img_path} ({e})")

print(f"\n✅ 完成，共处理 {counter - 1} 张图片，输出目录：{output_dir}")
